import React, { useEffect, useState } from "react";
import { type ReviveRuleMap, type ReviveRule, getRuleDisabled, getArguments } from "./revive";
import { Button, Card, Checkbox, Form, Input, Popover, Space } from "antd";
import { AllRuleInfoList } from "./rule";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { min_app_shell } from '@linksaas-minapp/api';



interface ReviveItemProps {
    ruleKey: keyof ReviveRuleMap;
    reviveRule: ReviveRule;
    enableAll: boolean;
    onRemove: () => void;
    onDisable: (disabled: boolean) => void;
    onChange: (args: unknown[]) => void;
}


export default function ReviveItem(props: ReviveItemProps) {
    const rule = AllRuleInfoList.find(rule => rule.id == props.ruleKey);
    const [ruleArgs, setRuleArgs] = useState(JSON.stringify(getArguments(props.reviveRule) ?? [], null, 2));
    const [hasChange, setHasChange] = useState(false);
    const [paramErr, setParamErr] = useState("");

    useEffect(() => {
        if (ruleArgs.trim() == "") {
            return;
        }
        try {
            const params = JSON.parse(ruleArgs) as unknown[];
            if (rule != undefined && rule.checkParam != undefined) {
                const errStr = rule?.checkParam(params) ?? "";
                setParamErr(errStr);
            }
        } catch (e) {
            console.log(e);
            setParamErr("参数配置不是合法的json格式")
        }
    }, [ruleArgs, rule]);


    if (rule == undefined) {
        return <></>;
    }
    return (
        <Card title={
            <Popover placement="right" trigger="hover" content={
                <div>
                    <p>{rule.descCn}</p>
                    <p>{rule.descEn}</p>
                </div>
            }>
                <span>{rule.name}({rule.id})&nbsp;<QuestionCircleOutlined /></span>
            </Popover>
        }
            style={{ marginBottom: "10px" }}
            extra={
                <Space>
                    <Button type="link" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        min_app_shell.openBrowser(`https://revive.run/r#${rule.id}`);
                    }}>规则详情</Button>
                    <Button type="primary" danger onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        props.onRemove();
                    }}>删除规则</Button>
                </Space>
            }>
            <Form labelCol={{ span: 5 }}>

                <Form.Item label="忽略这条规则">
                    <Checkbox checked={getRuleDisabled(props.reviveRule)} disabled={!props.enableAll} onChange={e => {
                        e.stopPropagation();
                        props.onDisable(e.target.checked);
                    }} />
                </Form.Item>


                {rule.paramList !== undefined && (
                    <Form.Item label="参数配置">
                        <ul>
                            {rule.paramList.map(param => (
                                <li key={param.id}>
                                    <h3>{param.id == "" ? "默认参数" : param.id}({param.paramType})</h3>
                                    <p>{param.descCn}</p>
                                    <p>{param.descEn}</p>
                                </li>
                            ))}
                            <li>
                                <h3>配置样例</h3>
                                <p>{JSON.stringify(rule.demoValue ?? [])}</p>
                            </li>
                        </ul>
                        <Input.TextArea value={ruleArgs} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setHasChange(true);
                            setRuleArgs(e.target.value);
                        }} disabled={getRuleDisabled(props.reviveRule)} rows={6} />
                        <div style={{ position: "relative", height: "20px" }}>
                            <div style={{ position: "absolute", right: "0px", top: "10px" }}>
                                <Space>
                                    <span style={{ color: "red" }}>{paramErr}</span>
                                    {hasChange == true && getRuleDisabled(props.reviveRule) == false && (
                                        <>
                                            <Button onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setRuleArgs(JSON.stringify(getArguments(props.reviveRule) ?? [], null, 2));
                                                setHasChange(false);
                                            }}>取消</Button>
                                            <Button type="primary" disabled={paramErr != ""} onClick={e => {
                                                //TODO
                                            }}>更新</Button>
                                        </>
                                    )}
                                </Space>
                            </div>
                        </div>

                    </Form.Item>
                )}
            </Form>
        </Card>
    );
}